10. Exercise: Create the GameViewModel
3 Exercise Create The GameViewModel 2020
Update note:
At timestamp 02:47, the video shows a now deprecated class ViewModelProviders as
viewModel = ViewModelProviders.of(fragment:this).get(GameViewModel::class.java).
Instead, use the ViewModelProvider as depicted here:
viewModel = ViewModelProvider(this).get(GameViewModel::class.java).
This is also shown in the instructions below.
Now it’s your turn to complete this exercise yourself.
In this exercise you'll be creating the GameViewModel, which will hold the UI-related data for your GameFragment.
1. Add lifecycle-extensions gradle dependency:
In the Module: app build.gradle file, add the lifecycle-extensions dependency. You can find the most current version of the dependency here.
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
Don't forget to sync!
2. Create the GameViewModel class, extending ViewModel:
Create a new file called GameViewModel.kt in the java/com.example.android.guesstheword/game package. Then in this file, create a class GameViewModel that extends ViewModel:
class GameViewModel : ViewModel()
3. Add init block and override onCleared. Add log statements to both:
Make an init block that prints out a log saying “GameViewModel created!”. Then override onCleared so you can track the lifetime of this ViewModel. You can use the keyboard shortcut Ctrl + O to do the override. Then add the log statement saying "GameViewModel destroyed!" to onCleared.
4.Create and initialize a GameViewModel, using ViewModelProvider(). Add a log statement:
Back in GameFragment use lateinit to create a field for GameViewModel called viewModel. Then in onCreateView, request the current GameViewModel using the ViewModelProvider class:
viewModel = ViewModelProvider(this).get(GameViewModel::class.java)
Add a log statement before calling viewModel, saying "Called ViewModelProvider()"
Finally, run your code, and make sure you see the expected logs. Rotate your device a few times and notice how the GameViewModel does not get created again.
If you want to start at this step, you can download this exercise code from: Step.01-Exercise-Create-the-GameViewModel.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.01-Solution-Create-the-GameViewModel or using this git diff.
Task Description:
Check the steps below as you implement them to complete this exercise.
Task Feedback:
Great work! You can check your solution against the solution we’ve provided here Step.01-Solution-Create-the-GameViewModel or using this git diff.
Reference documentation